package com.hqq.concurrency.half_syn_half_async;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.LinkedBlockingQueue;

/**
 * App
 * 半异步/半同步IO模式
 * 适用场景:
 * 1.UNIX网络子系统
 * 2.CORBA
 * 3.安卓异步框架
 * Created by heqianqian on 2017/8/9.
 */
public class App {

    private static final Logger LOGGER = LoggerFactory.getLogger(App.class);

    public static void main(String... args) {
        AsynchronousService service  = new AsynchronousService(new LinkedBlockingQueue<>());

        service.execute(new ArithmeticSumTask(1000));

        service.execute(new ArithmeticSumTask(500));
        service.execute(new ArithmeticSumTask(2000));
        service.execute(new ArithmeticSumTask(1));;
    }

    static class ArithmeticSumTask implements AsyncTask<Long> {

        private long mills;

        public ArithmeticSumTask(long mills) {
            this.mills = mills;
        }

        @Override
        public void onPreCall() {
            if (mills < 0) {
                throw new IllegalArgumentException("mills is less than 0");
            }
        }

        @Override
        public void onPostCall(Long result) {
            LOGGER.info(result.toString());
        }

        @Override
        public void onError(Throwable throwable) {
            throw new IllegalStateException("Should not occur");
        }

        @Override
        public Long call() throws Exception {
            return ap(mills);
        }
    }

    private static long ap(Long mills) {
        try {
            Thread.sleep(mills);
        } catch (InterruptedException e) {
            LOGGER.error("Exception caught.",e);
        }
        return mills * (mills + 1) / 2;
    }
}
